const express = require('express');
const cors = require('cors');

const app = express();
const port = 8082;

// 中间件
app.use(cors());
app.use(express.json());

// AI对话API
app.post('/api/v2/ai/chat', (req, res) => {
  console.log('AI Chat request:', req.body);
  
  const { message, userId, sessionId } = req.body;
  
  // 简单的AI回复逻辑
  let response = generateAIResponse(message);
  
  setTimeout(() => {
    res.json({
      code: 200,
      message: "success",
      data: {
        response: response,
        userId: userId,
        sessionId: sessionId,
        timestamp: Date.now()
      }
    });
  }, 500 + Math.random() * 1000);
});

// 数字人API
app.post('/api/v2/digital-human/generateCall', (req, res) => {
  console.log('Generate digital human call:', req.body);
  
  const { aiAgentId } = req.body;

  // 验证数字人智能体ID
  if (aiAgentId !== 'f97e8f48f6e64b679a977fb01bc9e28f') {
    return res.json({
      code: 400,
      message: `The specified agentId "${aiAgentId}" is not found.`,
      request_id: "error-" + Date.now()
    });
  }

  console.log(`✅ 使用数字人智能体ID: ${aiAgentId}, 地区: ${req.body.region || 'cn-beijing'}`);
  
  setTimeout(() => {
    res.json({
      code: 200,
      message: "success",
      data: {
        ai_agent_instance_id: "instance-" + Date.now(),
        channel_id: "channel-" + Date.now(),
        ai_agent_user_id: "agent-user-" + Date.now(),
        rtc_auth_token: "rtc-token-" + Date.now(),
        request_id: "request-" + Date.now(),
        agent_type: "AvatarAgent"
      }
    });
  }, 1000);
});

// 健康检查
app.get('/api/v2/digital-human/health', (req, res) => {
  res.json({
    code: 200,
    message: "success",
    data: {
      status: "UP",
      service: "digital-human-ai-chat",
      timestamp: Date.now()
    }
  });
});

// AI回复生成函数
function generateAIResponse(message) {
  const responses = {
    '你好': '您好！我是AI数字人助手，很高兴为您服务！',
    '您好': '您好！我是AI数字人助手，很高兴为您服务！',
    'hello': 'Hello! I am an AI digital human assistant!',
    '介绍': '我是一个AI数字人，可以与您进行自然对话。',
    '你是谁': '我是AI数字人助手，基于先进的人工智能技术。',
    '你能做什么': '我可以与您进行语音对话、回答问题、提供帮助。',
    '时间': `现在的时间是 ${new Date().toLocaleString('zh-CN')}`,
    '几点': `现在是 ${new Date().toLocaleTimeString('zh-CN')}`,
    '谢谢': '不客气！很高兴能够帮助您。',
    '再见': '再见！期待下次与您对话。'
  };
  
  const lowerMessage = message.toLowerCase().trim();
  
  for (const [key, value] of Object.entries(responses)) {
    if (lowerMessage.includes(key) || message.includes(key)) {
      return value;
    }
  }
  
  const defaultResponses = [
    '这是一个很有趣的问题，让我想想...',
    '我理解您的意思，不过我需要更多信息。',
    '这个话题很有意思，您能详细说说吗？',
    '感谢您的提问，我会努力给出更好的回答。'
  ];
  
  return defaultResponses[Math.floor(Math.random() * defaultResponses.length)];
}

// 启动服务器
app.listen(port, () => {
  console.log(`🚀 AI Chat Server running at http://localhost:${port}`);
  console.log('📋 Available endpoints:');
  console.log('  POST /api/v2/ai/chat - AI对话');
  console.log('  POST /api/v2/digital-human/generateCall - 生成数字人通话');
  console.log('  GET  /api/v2/digital-human/health - 健康检查');
  console.log('');
  console.log('🎤 支持真实语音识别和AI对话');
  console.log('🤖 服务器已启动，等待请求...');
});

// 保持进程运行
process.on('SIGINT', () => {
  console.log('\n👋 服务器正在关闭...');
  process.exit(0);
});
